﻿using System.IO;
using System;
using System.Runtime;
using System.Web;
using System.Web.UI;
using System.Security.Permissions;
using System.Reflection;


namespace Marbles.Core.Web.Resources
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class ResourceManager
    {

        protected string GetResourceUrl(Type ResourceStub, string Name)
        {
            Page pg = HttpContext.Current.CurrentHandler as Page;

            if (pg == null) { return string.Empty; }

            return pg.ClientScript.GetWebResourceUrl(ResourceStub, Name);
        }


        protected string GetResourceValue(Type ResourceStub, string Name)
        {

            Assembly assm = Assembly.GetAssembly(ResourceStub);
            string value = string.Empty;

            if (assm == null) { return null; }

            string[] resourceNames = assm.GetManifestResourceNames();

            foreach (string resourceName in resourceNames)
            {
                if (resourceName == Name)
                {
                    // The name of the resource Foo.txt will be prefixed with the name of the assembly.
                    string fooResourceName = Name;
                    using (Stream fooStream = assm.GetManifestResourceStream(fooResourceName))
                    {
                        using (StreamReader sr = new StreamReader(fooStream))
                        {
                            value = sr.ReadToEnd();
                        }
                    }
                }
            }

            return value;
        }
    }
}
